import router from './index';
import store from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import Layout from '@/layout/Layout.vue';
import storeUtils from '@/utils/storeUtils';

NProgress.configure({showSpinner: false});

const whiteList = ['/login'];
router.beforeEach((to, from, next) => {
  NProgress.start();
  store.commit('SET_BROWSER_HEADER_TITLE', to.name);
  if (to.query.token) {
    store.dispatch("setToken", to.query.token).then((response: any) => {
      console.log(response)
    });
    delete to.query.token;
  }
  if (!store.getters.projectInfo || store.getters.projectInfo.default) {
    store.dispatch('setProjectInfo').then((response: any) => {
      console.log(response)
    });
  }

  if (store.getters.token) {
    /* has token*/
    if (to.path === '/login') {
      next({path: '/'});
    } else {
      if (store.getters.routers.length === 0) {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          // 根据roles权限生成可访问的路由表
          routerGo(to, next);
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next({path: '/login'});
          });
        });
      } else {
        next();
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      storeUtils.clearStore();
      // if (store.getters.routers || store.getters.token) {
      //     location.reload(); // 为了重新实例化vue-router对象 避免bug
      // }
      next(`/login?redirect=${to.path}`); // 否则全部重定向到登录页
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
  setTimeout(() => {
    setTitle(store.getters.browserHeaderTitle);
  }, 10);
});


/**
 * 动态注册路由
 * @param to
 * @param next
 */
const routerGo = (to: any, next: any) => {
  const routers = store.getters.addRoutes;
  const getRouter = filterAsyncRouter(routers); // 过滤路由
  // 404路由需要放到最后面
  getRouter.push({
    path: '*',
    hidden: true,
    redirect: '/404',
  });

  getRouter.forEach(route => {
    router.addRoute(route); // 动态添加路由
  })
  next({...to, replace: true});
}

/**
 * 过滤处理路由
 * @param asyncRouterMap
 * @param path path
 * @returns {*}
 */
// 遍历后台传来的路由字符串，转换为组件对象
const filterAsyncRouter = (asyncRouterMap: any, path?: string | number): any => {
  const newRouter: any[] = [];
  asyncRouterMap.map((route: any) => {
    const newRoute = {...route};
    newRoute.children = [];
    if (newRoute.component) {
      // Layout组件特殊处理
      if (newRoute.component === 'Layout') {
        newRoute.component = Layout;//一级菜单
        if (route.children != null && route.children && route.children.length) {
          newRoute.index = 0;
          newRoute.children = filterAsyncRouter(route.children, 0);//二级或者三级菜单
        }
      } else {
        if (path && newRoute.visible === false) {
          newRoute.meta.activeMenu = path;
        }
        newRoute.component = loadView(newRoute.component);
        if (route.children != null && route.children && route.children.length) {//三级以上菜单
          if (!newRoute.children) {
            newRoute.children = [];
          }
          const children = filterAsyncRouter(route.children, path ? path : newRoute.path);
          if (!path) {
            newRouter.push(...children)
          } else {
            newRoute.children = children;
          }
        }
      }
    }
    newRouter.push(newRoute);
  });
  return newRouter
}


export const loadView = (view: string) => { // 路由懒加载
  return () => import(`@/views/${view}`);
};

/**
 * 设置浏览器头部标题
 */
const setTitle = (title: string): void => {
  title = title ? `${store.getters.projectInfo.name}  ${title}` : store.getters.projectInfo.name;
  window.document.title = title;
}
